<template>
  <div>
    <div>
      <el-upload class="upload-demo" ref="upload" action :show-file-list="false" :auto-upload="false" accept=".xlsx, .xls" :on-change="handleChange">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
    </div>

    <!-- 表格展示数据 -->
    <el-table :data="tableData" style="width: 100%" :height="600" border>
      <el-table-column prop="name" label="姓名" min-width="50%"> </el-table-column>
      <el-table-column prop="age" label="年龄" min-width="50%"> </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { readFile, character } from "@/utils"
import xlxs from "xlsx"
export default {
  name: "",
  data() {
    return {
      tableData: [],
    }
  },
  methods: {
    // 采集数据
    async handleChange(ev) {
      // 有文件才上传
      let file = ev.raw
      if (!file) return

      // 读取File中的数据
      let data = await readFile(file)
      let workbook = xlxs.read(data, { type: "binary" })
      console.log(workbook)
      // 表格
      let worksheet = workbook.Sheets[workbook.SheetNames[0]]
      // 将数据转化为json格式
      console.log(worksheet)
      data = xlxs.utils.sheet_to_json(worksheet)
      console.log(data)
      // 将json格式的值循环读取变为最后可以传递给服务器的数据
      let arr = []
      data.forEach((item) => {
        let obj = {}
        for (let key in character) {
          if (!character.hasOwnProperty(key)) break
          let v = character[key],
            text = v.text,
            type = v.type
          v = item[text] || ""
          type === "string" ? (v = String(v)) : null
          type === "number" ? (v = Number(v)) : null
          obj[key] = v
        }
        arr.push(obj)
      })
      console.log(arr)
      // 将数据呈现到页面上
      this.tableData = arr
    },

    // 数据上传到服务器
    async submitUpload() {
      if (this.tableData.length == 0) {
        return this.$message.warning("请选择要上传的文件")
      }

      // 将数据逐条传递
      let n = 0
      let send = async () => {
        if (n > this.tableData.length - 1) return // 数据都传递完成
        let body = this.tableData[n]
        // let result = await createAPI(body) 调用接口传递数据
        // 判断成功执行
        // if(result.errcode == 0){
        n++
        // }
        send()
      }
      send()
    },
  },
}
</script>
